
package com.example.demo.service.impl;


import com.example.demo.controller.vo.OrderDetailVo;
import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import com.example.demo.service.OrderService;
import com.example.demo.util.AjaxResult;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Resource
    private UserOrderMapper userOrderMapper;

    @Autowired
    private UserCourseMapper userCourseMapper;

    @Autowired
    private CourserMapper courserMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CourseInfoMapper courseInfoMapper;

    @Override
    public OrderPO getOrderDetailVo(String userId, long orderId) {
        return orderMapper.selectOrderByOrderId(orderId);
    }

    @Override
    public List<OrderPO> getOrderList(String userId, int status) {
        List<UserOrder> orderUser =  userOrderMapper.selectOrderList(userId,status);
        List<OrderPO> res = new ArrayList<>();
        for(UserOrder userOrder : orderUser){
            res.add(orderMapper.selectOrderByOrderId(userOrder.getOrderId()));
        }
        return res;
    }

//    @Override
//    public List<CoursePO> getCourseList(String userId, int status) {
//        return null;
//    }

    @Override
    public List<OrderPO> getOrderList(String userId) {
        List<UserOrder> userOrders =  userOrderMapper.selectOrderList1(userId);
        List<OrderPO> res = new ArrayList<>();
        for(UserOrder userOrder : userOrders){
            res.add(orderMapper.selectOrderByOrderId(userOrder.getOrderId()));
        }
        return res;
    }

    @Override
    public synchronized AjaxResult addOrder(String  userId, long courseId) {

        int random = new Random().nextInt(100000);

        // 获取课程信息
        CoursePO coursePO = courserMapper.selectCourseDetail(courseId);
        if(coursePO == null) {
            return new AjaxResult().error("没有该课程信息");
        }

        if(redisTemplate.hasKey(courseId + coursePO.getBeginTime() + random)){
            Set<String> userIdSet = (Set<String>) redisTemplate.opsForValue().get(courseId + coursePO.getBeginTime() + coursePO.getTime()+random);
            if(userIdSet != null){
                for(String id : userIdSet){
                    userOrderMapper.updateOrderStatusByStatusAndUserIdAndCourseId(id,OrderStatus.PINTUAN_READY,courseId,OrderStatus.PINTUAN_FAIL);
                }
            }
            redisTemplate.delete(courseId + coursePO.getBeginTime() + coursePO.getTime() + random);
            return new AjaxResult().error("拼单已经结束");
        }

        Set<String> userIdSet = (Set<String>) redisTemplate.opsForValue().get(courseId + coursePO.getBeginTime() + coursePO.getTime() + random);
        if(userIdSet == null){
            userIdSet = new HashSet<>();
        }
        userIdSet.add(userId);
        redisTemplate.opsForValue().set(courseId + coursePO.getBeginTime() + coursePO.getTime() + random,userIdSet);
        redisTemplate.opsForValue().set(courseId+coursePO.getBeginTime() +random,"拼团中", 2,TimeUnit.DAYS);

        // 更新销量
        coursePO.setSaleNums(coursePO.getSaleNums() + 1);
        coursePO.setReadySum(coursePO.getReadySum() + 1);
        courserMapper.updateCourseByCourseId(coursePO);

        // 新增订单详情
        OrderPO orderPO = new OrderPO();
        orderPO.setBeginTime(orderPO.getBeginTime());
        orderPO.setCreateTime(System.currentTimeMillis());
        orderPO.setUpdateTime(System.currentTimeMillis());
        orderPO.setRealCost(coursePO.getRealCost());
        orderPO.setImgUrl(coursePO.getImgUrl());
        orderPO.setSaleNums(coursePO.getSaleNums());
        orderPO.setReadySum(coursePO.getReadySum());
        orderPO.setTag(coursePO.getTag());
        orderPO.setTime(coursePO.getTime());
        orderPO.setTitle(coursePO.getTitle());
        orderPO.setTotalSum(coursePO.getTotalSum());
        orderMapper.addOrder(orderPO);

        // 新增用户订单表
        UserOrder userOrder = new UserOrder();
        userOrder.setOrderId(orderPO.getId());
        userOrder.setUpdateTime(System.currentTimeMillis());
        userOrder.setCreateTime(System.currentTimeMillis());
        userOrder.setUserId(userId);
        userOrder.setCourseId(courseId);
        if(coursePO.getTotalSum() == coursePO.getReadySum()){
            userOrder.setStatus(OrderStatus.PINTUAN_FINISH);
            Set<String> userIdSets = (Set<String>) redisTemplate.opsForValue().get(courseId + coursePO.getBeginTime() + coursePO.getTime());
            if(userIdSets != null){
                for(String id : userIdSets){
                    if(id == userId){
                        continue;
                    }
                    userOrderMapper.updateOrderStatusByStatusAndUserIdAndCourseId(id,OrderStatus.PINTUAN_READY,courseId,OrderStatus.PINTUAN_FINISH);
                }
            }
            userOrder.setStatus(OrderStatus.PINTUAN_FINISH);
            redisTemplate.delete(courseId + coursePO.getBeginTime() + coursePO.getTime());
        }else {
            userOrder.setStatus(OrderStatus.PINTUAN_READY);
        }
        userOrderMapper.add(userOrder);

        // 新增用户课程
        UserCourse userCourse = new UserCourse();
        userCourse.setCourseId(courseId);
        userCourse.setUserId(userId);
        userCourse.setCreateTime(System.currentTimeMillis());
        userCourse.setUpdateTime(System.currentTimeMillis());
        userCourseMapper.addCourse(userCourse);

        // 返回账号密码
        CourseInfo courseInfo = courseInfoMapper.selectCourseInfoByCId(courseId);
        return new AjaxResult().ok(courseInfo);
    }
}
